<template>
  <div class="page">
    <label for>{{label}}</label>
    <div>
      <slot></slot>
      <p v-if="errStatus">{{errMessage}}</p>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import Schema from "async-validator";
export default {
  inject: ["mForm"],
  props: {
    label: {
      type: String,
      default: ""
    },
    prop: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      errStatus: false,
      errMessage: ""
    };
  },
  mounted() {
    this.$on("validate", this.validator);
    if (this.prop) {
      this.$parent.$emit("formItemAdd", this);
    }
  },
  methods: {
    validator() {
      return new Promise((resolve, reject) => {
        const rules = this.mForm.rules[this.prop];
        const value = this.mForm.model[this.prop];
        const descriptor = { [this.prop]: rules };
        const schema = new Schema(descriptor);
        schema.validate({ [this.prop]: value }, errors => {
          if (errors) {
            this.errStatus = true;
            this.errMessage = errors[0].message;
            resolve(false);
          } else {
            this.errStatus = false;
            this.errMessage = "";
            resolve(true);
          }
        });
      });
    }
  },
  components: {}
};
</script>

<style scoped>
</style>
